package com.biz.primus.ms.promotion.dao.redis;

import com.biz.primus.ms.promotion.dao.ro.SeckillPromotionRo;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import org.springframework.stereotype.Repository;

/**
 * 秒杀活动Redis Dao
 *
 * @author david-liu
 */
@Repository
public class SeckillPromotionRedisDao extends BasePromotionRedisDao<SeckillPromotionRo, Long> {

    /**
     * 获取今日设置的秒杀活动
     *
     * @return 秒杀活动
     */
    public List<SeckillPromotionRo> getTodayAvailableSeckillPromotions() {
        Set<byte[]> idBytes = super.zRange(this.getDateSeckillPromotionSortedSetKey(DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now())), 0, -1);
        return Optional.ofNullable(super.findByIds(idBytes)).orElse(Collections.emptyList());
    }

    /**
     * 批量获取秒杀活动商品信息
     *
     * @param promotionIds 秒杀活动ID集合
     * @return 商品集合
     */
    public Map<Long, List<Long>> getPromotionProducts(List<Long> promotionIds) {
        return super.getPromotionProducts(promotionIds, this::getSeckillPromotionProductSortedSetKey);
    }

    /**
     * 获取日期内可用秒杀活动SortedSet Key
     *
     * @param date 日期
     * @return SortedSet Key
     */
    private String getDateSeckillPromotionSortedSetKey(String date) {
        return super.getKeyByParams("date", date);
    }

    /**
     * 获取秒杀活动商品SortedSet Key
     *
     * @param promotionId 活动ID
     * @return SortedSet Key
     */
    private String getSeckillPromotionProductSortedSetKey(Long promotionId) {
        return getKeyByParams(promotionId, "prds");
    }
}
